

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言  编码过程中，读者肯定会遇到一些IO类型的操作。  什么是IO？就是比如文件操作、网络请求。  往往这类操作，都需要被操作对象，比如：  文件操作，需要打开一个文件，存放在内存中 网络请求，需要一个request 数据库链接，需要一个db实例化对象还有一个游标cur      这些对象，操作前都会有一个open或connect的动作，操作结束后，都会有一个close。  在with关键字不被">
<meta property="og:type" content="article">
<meta property="og:title" content="with -- 优雅永不过时">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2022/07/16/python/advanced/with/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言  编码过程中，读者肯定会遇到一些IO类型的操作。  什么是IO？就是比如文件操作、网络请求。  往往这类操作，都需要被操作对象，比如：  文件操作，需要打开一个文件，存放在内存中 网络请求，需要一个request 数据库链接，需要一个db实例化对象还有一个游标cur      这些对象，操作前都会有一个open或connect的动作，操作结束后，都会有一个close。  在with关键字不被">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-07-16T06:10:05.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.264Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="Python进阶">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>with -- 优雅永不过时 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="with -- 优雅永不过时"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-07-16 14:10" pubdate>
          2022年7月16日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          3.3k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">with -- 优雅永不过时</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>  编码过程中，读者肯定会遇到一些<strong>IO</strong>类型的操作。<br>  什么是<strong>IO</strong>？就是比如文件操作、网络请求。<br>  往往这类操作，都需要被操作对象，比如：</p>
<ul>
<li>文件操作，需要打开一个文件，存放在内存中</li>
<li>网络请求，需要一个request</li>
<li>数据库链接，需要一个db实例化对象还有一个游标cur  </li>
</ul>
<p>  这些对象，操作前都会有一个<code>open</code>或<code>connect</code>的动作，操作结束后，都会有一个<code>close</code>。<br>  在<em><strong>with</strong></em>关键字不被熟知之前，一般都是使用<code>try-finally</code>来进行操作前后的初始化和收尾工作。<br>  所以本文章会专门介绍<strong>with</strong>语法，以及<strong>被操作对象</strong>如何实现。</p>
<h2 id="基础语法"><a href="#基础语法" class="headerlink" title="基础语法"></a>基础语法</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;yourFilePath&#x27;</span>, <span class="hljs-string">&#x27;w&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>) <span class="hljs-keyword">as</span> obj:<br>    ...<br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">witn [action obj] as [rename]:</span><br><span class="hljs-string">    your code</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>
<h3 id="工作流程"><a href="#工作流程" class="headerlink" title="工作流程"></a>工作流程</h3><ul>
<li>通过<strong>with</strong>构建一个操作对象，通过as赋值给一个变量</li>
<li>在缩进代码块中，你可以对该变量进行操作</li>
<li>在代码块运行结束后(不论是正常结束还是异常结束)，会自动帮你将对象<code>close</code>(有前提)。</li>
</ul>
<p>  针对工作流程的<strong>第二点</strong>，如果<strong>操作对象</strong>可以通过with进行自动关闭，那么在代码块外再调用实例化后的<code>obj</code>，将无法对其进行操作。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;./text.txt&#x27;</span>, <span class="hljs-string">&#x27;r&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>) <span class="hljs-keyword">as</span> f:<br>    <span class="hljs-built_in">print</span>(f.read())  <span class="hljs-comment"># 正常操作，我创建的文件内容为123</span><br><span class="hljs-built_in">print</span>(f.read())  <span class="hljs-comment"># 会报错</span><br><br><span class="hljs-comment"># 运行结果</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">123</span><br><span class="hljs-string">ValueError: I/O operation on closed file.</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>
<p>  针对工作流程的<strong>第三点</strong>的<em><strong>不论是正常结束还是异常结束</strong></em>，我们可以看下面这个例子:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">try</span>:<br>    <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;./text.txt&#x27;</span>, <span class="hljs-string">&#x27;r&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>) <span class="hljs-keyword">as</span> f:<br>        <span class="hljs-comment"># 手动触发异常</span><br>        <span class="hljs-keyword">raise</span> EOFError<br><span class="hljs-keyword">except</span>:<br>    ...<br><br><span class="hljs-built_in">print</span>(f.read())<br><br><span class="hljs-comment"># 运行结果</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">ValueError: I/O operation on closed file.</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>
<p>  可以看见，文件已经正常关闭了，不会因为异常而影响文件关闭。</p>
<h2 id="工作原理"><a href="#工作原理" class="headerlink" title="工作原理"></a>工作原理</h2><p>  <strong>with</strong>关键字在<strong>python</strong>中叫做<em><strong>上下文管理器</strong></em>，其<strong>被操作对象</strong>需要实现【上下文协议】，只有实现了这个协议，才能被with正常的打开和关闭。</p>
<h3 id="上下文协议"><a href="#上下文协议" class="headerlink" title="上下文协议"></a>上下文协议</h3><p>   万物皆可对象的python，想要实现【上下文协议】当然是离不开类以及类中的魔法方法：</p>
<ul>
<li>__enter__ with赋值会调用这个方法</li>
<li>__exit__  with结束会调用这个方法</li>
</ul>
<p>   我们可以直接来看下面这个例子：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestContext</span>():<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__enter__</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;调用了__enter__&quot;</span>)<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;我被打开了&quot;</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__exit__</span>(<span class="hljs-params">self, exc_type, exc_val, exc_tb</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;调用了__exit__&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我要被关闭咯&quot;</span>)<br><br><br><span class="hljs-keyword">with</span> TestContext() <span class="hljs-keyword">as</span> obj:<br>    <span class="hljs-built_in">print</span>(obj)<br><br><span class="hljs-keyword">with</span> TestContext() <span class="hljs-keyword">as</span> obj:<br>    <span class="hljs-keyword">raise</span> Exception <span class="hljs-comment"># 手动触发一个异常，看看能否正常关闭</span><br><br><span class="hljs-comment"># 运行结果</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">调用了__enter__</span><br><span class="hljs-string">我被打开了</span><br><span class="hljs-string">调用了__exit__</span><br><span class="hljs-string">我要被关闭咯</span><br><span class="hljs-string">调用了__enter__</span><br><span class="hljs-string">调用了__exit__</span><br><span class="hljs-string">我要被关闭咯</span><br><span class="hljs-string">Traceback (most recent call last):</span><br><span class="hljs-string">  File &quot;C:/Users/sasa/Desktop/test/update.py&quot;, line 15, in &lt;module&gt;</span><br><span class="hljs-string">    raise Exception # 手动触发一个异常，看看能否正常关闭</span><br><span class="hljs-string">Exception</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>
<p>可以看得出来，<code>__exit__</code>的触发，其实是在触发异常之前。这就不难解释为啥即使异常了，也不会影响对象正常的关闭。<code>__exit__</code>中的默认参数，分别代表：</p>
<ul>
<li>exc_type：异常类型</li>
<li>exc_value：异常对象</li>
<li>exc_tb：异常堆栈信息</li>
</ul>
<p>我们可以根据异常的不同，分别进行收尾处理。</p>
<h2 id="with应用场景"><a href="#with应用场景" class="headerlink" title="with应用场景"></a>with应用场景</h2><p>  <strong>with</strong>最常遇到的应用场景，应该是<strong>文件操作</strong>了吧。<br>  但是编程嘛，不加入一些自己的封装，那还叫编程嘛？<br>  所以作者基于自己的见解，总结出一些<strong>with</strong>可以使用的额外场景：</p>
<h3 id="场景一：没有实现上下文协议的对象，二次封装实现自动关闭"><a href="#场景一：没有实现上下文协议的对象，二次封装实现自动关闭" class="headerlink" title="场景一：没有实现上下文协议的对象，二次封装实现自动关闭"></a>场景一：没有实现上下文协议的对象，二次封装实现自动关闭</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> selenium <span class="hljs-keyword">import</span> webdriver<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">DriverContext</span>():<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):<br>        self.driver = webdriver.Chrome()<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__enter__</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-comment"># 进行一些driver初始化操作。当然你可以放在__init__中进行</span><br>        self.driver.maximize_window()<br>        self.driver.implicitly_wait(<span class="hljs-number">10</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__exit__</span>(<span class="hljs-params">self, exc_type, exc_val, exc_tb</span>):<br>        self.driver.quit()<br><br><span class="hljs-keyword">with</span> DriverContext() <span class="hljs-keyword">as</span> driver:<br>    driver.get(<span class="hljs-string">&quot;xxx&quot;</span>)<br>        <br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">通过阅读webdriver的源码我们得知</span><br><span class="hljs-string">driver实例化对象的类中，是没有实现 上下文协议 的</span><br><span class="hljs-string">我们可以基于 上下文协议 ，自己封装一个类，去编写自己的脚本、工具</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<h3 id="场景二：请求截断处理"><a href="#场景二：请求截断处理" class="headerlink" title="场景二：请求截断处理"></a>场景二：请求截断处理</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> requests<br><br><span class="hljs-comment"># 以下均为伪代码, 不能直接拿来运行，只是提供思路</span><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">RequestHandle</span>():<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, requestObj</span>):<br>        self.requestObj = requestObj<br>        self.req = requests<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__enter__</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-keyword">return</span> self.req  <span class="hljs-comment"># 将新的请求对象实例化</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__exit__</span>(<span class="hljs-params">self, exc_type, exc_val, exc_tb</span>):<br>        <span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">        遇到异常，将原请求发送</span><br><span class="hljs-string">        &quot;&quot;&quot;</span><br>        <span class="hljs-keyword">if</span> exc_type:<br>            self.req.request(**self.requestObj)<br><br>requestObj = &#123;<br>    <span class="hljs-string">&#x27;method&#x27;</span>: <span class="hljs-string">&#x27;post&#x27;</span>,<br>    <span class="hljs-string">&#x27;url&#x27;</span>: <span class="hljs-string">&#x27;xxx&#x27;</span>,<br>    <span class="hljs-string">&#x27;data&#x27;</span>: &#123;<br><br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">with</span> RequestHandle(requestObj) <span class="hljs-keyword">as</span> req:<br>    <span class="hljs-comment"># 篡改数据或其他的一些代码</span><br>    req.post(<br>        url=<span class="hljs-string">&#x27;xxx&#x27;</span>,<br>        data=&#123;&#125;<br>    )<br></code></pre></td></tr></table></figure>
<p>以上的代码思路可以用作收发消息的<em>第三方客户端</em>。<br>正常的客户端，收到<code>socket</code>消息后，将消息发送到另一个地方，如果有需要，进行数据的篡改，但是又不能影响到消息的正常发送。<br>我们就可以基于客户端原有的<em>tcp协议</em>，进行脚本工具的二次开发。通过上下文协议配合with进行消息的处理转发。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/python/" class="category-chain-item">python</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/python/Python%E8%BF%9B%E9%98%B6/" class="category-chain-item">Python进阶</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/Python%E8%BF%9B%E9%98%B6/">#Python进阶</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>with -- 优雅永不过时</div>
      <div>https://walker_kwu.gitee.io/my-blog/2022/07/16/python/advanced/with/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年7月16日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2022/07/21/python/advanced/%E6%8E%A8%E5%AF%BC%E5%BC%8F/" title="推导式 -- 更高效地生成数据">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">推导式 -- 更高效地生成数据</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2022/07/13/python/advanced/decorators/" title="Decorators(装饰器 -- 让你的代码更python范儿)">
                        <span class="hidden-mobile">Decorators(装饰器 -- 让你的代码更python范儿)</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
